// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const axios = require('axios');
const crypto = require('crypto');
async function cloudDownFile(fileUrl){
  return new Promise(function(resolve,reject){
    axios({
      method: 'GET',
      url: fileUrl,
      responseType:"arraybuffer",
      headers: {
        "content-type": "application/octet-stream"
      }
    }).then(response => {
      // console.log(response)
      let contentType = response.headers['content-type']
      resolve({
        contentType,
        data:response.data
      })
    })
  })
}
// 云函数入口函数
exports.main = async (event, context) => {
  let url = event.url;
  /**获取文件类型 */
  let baseData = await cloudDownFile(url)
  let fileStream = baseData.data;
  console.log(baseData.contentType)
  /**定义文件类型 */
  let fileType = '';
  if(baseData.contentType == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'){
    fileType = 'docx'
  }else{
    fileType = 'pdf'
  }
  const hash = crypto.createHash('md5');
  hash.update(fileStream, 'utf8');
  const md5 = hash.digest('hex');
  console.log('--文件唯一MD5编码--')
  console.log(md5);
  // console.log(fileStream)
  let upData = await cloud.uploadFile({
    cloudPath: 'edu-files/'+md5+'.'+fileType,
    fileContent: Buffer.from(fileStream,'base64')
  })
  return upData;
}